<?php

namespace App\Models\Member;

use App\Models\BaseModel;
use App\Common\AliossHandler;
use App\Models\Member\NoticeRecord;
use Carbon\Carbon;
use Auth;

class Notice extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'title', 'cover', 'detail',
        'status', 'begin_at', 'end_at', 'created_at', 'updated_at'
    ];

    public function getList()
    {
        $user = Auth::user()->toArray();
        $data = $this->where('store_id', $user['store_id'])
                 ->where('status', 1)
                 ->orderBy('id', 'desc')
                 ->paginate(10)
                 ->toArray();

        foreach ($data['data'] as $key => $v) {
            $data['data'][$key]['cover'] = AliossHandler::read('notice', $v['cover']);
        }

        return $data;
    }

    public function getDetail($id)
    {
        $notice = $this->find($id)->toArray();
        $notice['cover'] = AliossHandler::read('notice', $notice['cover']);

        return $notice;
    }

    public function getNotice()
    {
        $today = Carbon::today();
        $user = Auth::user();
        $ids = NoticeRecord::where('store_id', $user->store_id)
                                  ->where('user_id', $user->id)
                                  ->select(['notice_id'])
                                  ->get()
                                  ->toArray();
        $ids = array_column($ids, 'notice_id');

        $notice = $this->where('status', 1)
                       ->where('begin_at', '<=', $today)
                       ->where('end_at', '>=', $today)
                       ->whereNotIn('id', $ids)
                       ->get()
                       ->toArray();

        foreach ($notice as $key => $v) {
            $notice[$key]['cover'] = AliossHandler::read('notice', $v['cover']);
        }
        return $notice;
    }

    public function saveRecord($id)
    {
        $user = Auth::user();
        $hasRecord = NoticeRecord::where('store_id', $user->store_id)
                                  ->where('user_id', $user->id)
                                  ->where('notice_id', $id)
                                  ->exists();
        if($hasRecord) return true;

        $noticeRecord = new NoticeRecord;
        $noticeRecord->create([
            'store_id' => $user->store_id,
            'user_id' => $user->id,
            'notice_id' => $id
        ]);
        return true;
    }
}
